import React, {
    useState,
    useEffect,
    useRef,
    useImperativeHandle,
    forwardRef,
} from 'react';
import { Table, Input, Select, Tooltip, Popconfirm, Button } from 'antd';
import { ExclamationCircleOutlined, DeleteOutlined } from '@ant-design/icons';
import './index.less';

interface FieldRule {
    validator: (value: any, rowData: any, rowIndex: number) => Promise<string>;
}

interface ColumnProps {
    fieldType?: 'Select' | 'Input';
    fieldRules?: FieldRule[];
    dataIndex: string;
    title: string;
    render?: (text: any, record: any, index: number) => React.ReactNode;
    [key: string]: any;
}

interface TableInputProps {
    value?: any[];
    onChange?: (value: any[]) => void;
    columns: ColumnProps[];
    autoAddRow?: boolean; // 是否在最后一行输入时自动添加新行
    defaultNewRow?: () => any; // 新行的默认数据生成函数
}

export interface TableInputRef {
    validateFields: () => Promise<any[]>;
}

const TableInput = forwardRef<TableInputRef, TableInputProps>(
    (
        { value = [], onChange, columns, autoAddRow = true, defaultNewRow },
        ref,
    ) => {
        const [data, setData] = useState<any[]>(value);
        const [errors, setErrors] = useState<
            Record<string, Record<string, string>>
        >({});
        const [hoveredCell, setHoveredCell] = useState<{
            rowIndex: number;
            dataIndex: string;
        } | null>(null);

        useEffect(() => {
            setData(value);
        }, [value]);

        const handleChange = (
            rowIndex: number,
            dataIndex: string,
            newValue: any,
        ) => {
            const newData = [...data];
            newData[rowIndex] = {
                ...newData[rowIndex],
                [dataIndex]: newValue,
                isNewRow: false, // 一旦编辑，就不再是新行
            };

            onChange?.(newData);

            // 验证字段
            validateField(rowIndex, dataIndex, newValue, newData[rowIndex]);

            // 如果启用了自动添加行功能，并且当前修改的是最后一行，则自动添加新行
            if (autoAddRow && rowIndex === data.length - 1) {
                // 检查最后一行是否有输入内容（任意字段非空）
                const lastRow = newData[rowIndex];
                const hasInput = Object.keys(lastRow).some((key) => {
                    if (key === 'isNewRow') return false; // 忽略 isNewRow 字段
                    const value = lastRow[key];
                    return (
                        value !== null && value !== undefined && value !== ''
                    );
                });

                if (hasInput) {
                    // 创建新行
                    let newRow: any = {};

                    if (defaultNewRow) {
                        // 使用提供的默认行生成函数
                        newRow = defaultNewRow();
                        // 添加新行标记
                        newRow.isNewRow = true;
                    }

                    const updatedData = [...newData, newRow];
                    onChange?.(updatedData);
                }
            }
        };

        // 校验单个字段
        const validateField = async (
            rowIndex: number,
            dataIndex: string,
            value: any,
            rowData: any,
        ) => {
            // 如果是新行，跳过校验
            if (rowData.isNewRow) return;

            const column = columns.find((col) => col.dataIndex === dataIndex);
            if (!column?.fieldRules) return;

            const newErrors = { ...errors };
            if (!newErrors[rowIndex]) {
                newErrors[rowIndex] = {};
            }

            try {
                for (const rule of column.fieldRules) {
                    const errorMessage = await rule.validator(
                        value,
                        rowData,
                        rowIndex,
                    );
                    if (errorMessage) {
                        newErrors[rowIndex][dataIndex] = errorMessage;
                        setErrors(newErrors);
                        return;
                    }
                }

                // 验证通过，清除错误
                if (newErrors[rowIndex][dataIndex]) {
                    delete newErrors[rowIndex][dataIndex];
                    setErrors(newErrors);
                }
            } catch (error) {
                newErrors[rowIndex][dataIndex] =
                    error instanceof Error ? error.message : '验证失败';
                setErrors(newErrors);
            }
        };

        const renderCell = (
            text: any,
            record: any,
            rowIndex: number,
            dataIndex: string,
            fieldType?: 'Input' | 'Select',
        ) => {
            const hasError = errors[rowIndex]?.[dataIndex];
            const isHovered =
                hoveredCell?.rowIndex === rowIndex &&
                hoveredCell?.dataIndex === dataIndex;

            const cellProps = {
                className: `table-input-cell ${hasError ? 'has-error' : ''} ${
                    isHovered ? 'is-hovered' : ''
                }`,
                onMouseEnter: () => setHoveredCell({ rowIndex, dataIndex }),
                onMouseLeave: () => setHoveredCell(null),
            };

            const errorIcon = hasError ? (
                <Tooltip title={errors[rowIndex][dataIndex]}>
                    <ExclamationCircleOutlined className="error-icon" />
                </Tooltip>
            ) : null;

            if (fieldType === 'Input') {
                return (
                    <div {...cellProps}>
                        <Input
                            value={text}
                            onChange={(e) =>
                                handleChange(
                                    rowIndex,
                                    dataIndex,
                                    e.target.value,
                                )
                            }
                            bordered={false}
                        />
                        {errorIcon}
                    </div>
                );
            } else if (fieldType === 'Select') {
                // 这里假设 Select 的选项是通过 column 的 options 属性传入的
                const options =
                    (columns.find((col) => col.dataIndex === dataIndex) as any)
                        ?.options || [];

                return (
                    <div {...cellProps}>
                        <Select
                            value={text}
                            onChange={(value) =>
                                handleChange(rowIndex, dataIndex, value)
                            }
                            bordered={false}
                            style={{ width: '100%' }}
                            options={options}
                        />
                        {errorIcon}
                    </div>
                );
            }

            return text;
        };

        const tableColumns = columns.map((column) => {
            const { fieldType, fieldRules, ...restColumnProps } = column;

            return {
                ...restColumnProps,
                render: (text: any, record: any, index: number) => {
                    if (column.render) {
                        return column.render(text, record, index);
                    }

                    return renderCell(
                        text,
                        record,
                        index,
                        column.dataIndex,
                        fieldType,
                    );
                },
            };
        });

        // 删除行
        const handleDeleteRow = (rowIndex: number) => {
            const newData = [...data];
            newData.splice(rowIndex, 1);
            onChange?.(newData);
        };
        tableColumns.push({
            title: '操作',
            // @ts-ignore
            key: 'action',
            width: 100,
            render: (text: any, record: any, index: number) => (
                <Popconfirm
                    title="确定要删除这行数据吗？"
                    onConfirm={() => handleDeleteRow(index)}
                    okText="确定"
                    cancelText="取消"
                >
                    <Button
                        type="link"
                        danger
                        icon={<DeleteOutlined />}
                        size="small"
                    >
                        删除
                    </Button>
                </Popconfirm>
            ),
        });

        // 校验所有字段
        const validateFields = async (): Promise<any[]> => {
            const newErrors: Record<string, Record<string, string>> = {};
            let hasError = false;

            // 遍历所有行和需要校验的列
            for (let rowIndex = 0; rowIndex < data.length; rowIndex++) {
                const rowData = data[rowIndex];

                // 如果是新行，跳过校验
                if (rowData.isNewRow) continue;

                for (const column of columns) {
                    if (!column.fieldRules) continue;

                    const dataIndex = column.dataIndex;
                    const value = rowData[dataIndex];

                    // 对每个字段应用所有验证规则
                    for (const rule of column.fieldRules) {
                        try {
                            const errorMessage = await rule.validator(
                                value,
                                rowData,
                                rowIndex,
                            );
                            if (errorMessage) {
                                if (!newErrors[rowIndex]) {
                                    newErrors[rowIndex] = {};
                                }
                                newErrors[rowIndex][dataIndex] = errorMessage;
                                hasError = true;
                                break; // 一旦有错误，跳过该字段的其他规则
                            }
                        } catch (error) {
                            if (!newErrors[rowIndex]) {
                                newErrors[rowIndex] = {};
                            }
                            newErrors[rowIndex][dataIndex] =
                                error instanceof Error
                                    ? error.message
                                    : '验证失败';
                            hasError = true;
                            break;
                        }
                    }
                }
            }

            // 更新错误状态
            setErrors(newErrors);

            // 如果有错误，抛出异常
            if (hasError) {
                throw new Error('表单验证失败');
            }

            // 返回验证通过的数据
            return data;
        };

        // 暴露方法给父组件
        useImperativeHandle(ref, () => ({
            validateFields,
        }));

        return (
            <div className="table-input-container">
                <Table
                    dataSource={data}
                    columns={tableColumns}
                    pagination={false}
                    rowKey={(record, index) => index?.toString() || '0'}
                />
            </div>
        );
    },
);

export default TableInput;
